package cn.xiuminglee.tools.modules.word.biz.translate;

import cn.xiuminglee.tools.core.exception.MingToolsException;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * @author xiuming
 * 百度翻译官方demo 使用的HttpGet
 */
@Slf4j
public class HttpGet {
    /** 10S */
    protected static final int SOCKET_TIMEOUT = 10000;
    protected static final String GET = "GET";

    public static String get(String host, Map<String, String> params) throws Exception {
        // 设置SSLContext
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[]{myX509TrustManager}, null);

        String sendUrl = getUrlWithQueryString(host, params);

        // 创建URL对象
        URL uri = new URL(sendUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        if (conn instanceof HttpsURLConnection) {
            ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
        }

        // 设置相应超时
        conn.setConnectTimeout(SOCKET_TIMEOUT);
        conn.setRequestMethod(GET);
        int statusCode = conn.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new MingToolsException("Http错误码：" + statusCode);
        }

        // 读取服务器的数据
        InputStream is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            builder.append(line);
        }

        String text = builder.toString();

        close(br);
        close(is);
        conn.disconnect();

        return text;
    }

    public static String getUrlWithQueryString(String url, Map<String, String> params) throws UnsupportedEncodingException {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) {
                // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    protected static void close(Closeable closeable) throws IOException {
        if (closeable != null) {
            closeable.close();
        }
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) throws UnsupportedEncodingException {
        if (input == null) {
            return "";
        }
        return URLEncoder.encode(input, "utf-8");
    }

    private static TrustManager myX509TrustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

}
